package com.lh.web.service.impl.shop;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.lh.common.entity.admin.Category;
import com.lh.common.utils.PageUtils;
import com.lh.web.dao.admin.CategoryMapper;
import com.lh.web.service.serviceAdmin.shop.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author FH
 * @ClassName: CategoryServiceImpl
 * @Description: (类作用)
 * @date: 2020-06-28 9:20
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public PageUtils queryCategoryList(Map<String, Object> param, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        param.put("sortParentId",0);
        List<Category> page = this.baseMapper.queryCategoryList(param);
        if(CollectionUtils.isEmpty(page)){
            return null;
        }
        for (Category category:page){
            Long count = 0l;
            //一级的下级分类
            Map<String, Object> map = new HashMap<>(2);
            map.put("sortParentId",category.getId());
            List<Category> categories = this.baseMapper.queryCategoryList(map);
            for (Category cate:categories){
                count += cate.getCon();
                //一级的下级分类
                Map<String, Object> map1 = new HashMap<>(2);
                map1.put("sortParentId",cate.getId());
                List<Category> categories1 = this.baseMapper.queryCategoryList(map1);
                for (Category cate1:categories1){
                    count += cate1.getCon();
                    cate1.setType(3);
                }
                cate.setChildren(categories1);
                cate.setCon(count);
                cate.setType(2);
            }
            category.setType(1);
            category.setChildren(categories);
            category.setCon(count+category.getCon());
        }
        return new PageUtils(page);
    }

    @Override
    public Category getCategoryName(String sortName) {
        return this.baseMapper.getCategoryName(sortName);
    }

    @Override
    public int addCategory(Category category) {
        return this.baseMapper.addCategory(category);
    }

    @Override
    public int updateCategory(Category category) {
        return this.baseMapper.updateCategory(category);
    }

    @Override
    public String deleteCategory(Long id) {
        List<Map<String, Object>> maps = this.baseMapper.querySortParent(id);
        int i = this.baseMapper.queryShopCount(id);
        if(i > 0){
            return "此类目（子类目）下关联有商品，不可删除！";
        }
        for (Map map: maps){
            this.baseMapper.deleteCategory(Long.parseLong(map.get("id").toString()));
        }
        return "";
    }
}
